<template>
  <div id="app" class="app-wrap">
    <!-- 顶部操作区：发布公告 + 搜索栏 -->
    <div class="tool-bar">
    <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogVisible = true">
  发布公告
      </el-button>

      <el-form :inline="true" size="small" style="margin-left: auto;">
        <el-form-item style="margin-bottom: 0;">
          <el-input
            v-model="keyword"
            placeholder="请输入公告名称"
            clearable
            style="width: 220px"
            @clear="fetchTable"
            @keyup.enter.native="fetchTable"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0;">
          <el-button type="primary" @click="fetchTable">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      size="small"
      style="width: 100%"
      header-cell-class-name="table-head"
    >
      <el-table-column label="公告名称" min-width="180">
      <template #default="{ row }">{{ row.noticeName }}</template>
    </el-table-column>

      <el-table-column label="公告分类" width="100">
        <template #default="{ row }">{{ row.noticeCategoryName }}</template>
      </el-table-column>

      <el-table-column label="关联小区" width="120">
        <template #default="{ row }">{{ row.communityName }}</template>
      </el-table-column>

      <el-table-column label="发布时间" width="160">
        <template #default="{ row }">{{ row.noticeTime }}</template>
      </el-table-column>

      <el-table-column label="状态" width="90">
        <template #default="{ row }">
          <el-tag :type="row.noticeStatus === 1 ? 'success' : 'info'" size="mini">
            {{ row.noticeStatus === 1 ? '已发布' : '未发布' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="发布人" width="100">
        <template #default="{ row }">{{ row.noticePerson }}</template>
      </el-table-column>

      <el-table-column label="是否置顶" width="70">
        <template #default="{ row }">
          <el-tag v-if="row.top" type="danger" size="mini">是</el-tag>
          <span v-else>否 </span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="130">
        <template #default="{ row,$index }">
          <el-button type="text" size="mini" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" size="mini" style="color:#f56c6c" @click="handleDel(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[3,5, 6, 9]"
        :page-size="pageSize"
        :total="total"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

     <!-- 发布公告弹窗 -->
   <el-dialog 
  title="发布公告" 
  :visible.sync="dialogVisible" 
  width="500px"
>
  <el-form :model="form" label-width="100px">
    <el-form-item label="公告名称">
      <el-input v-model="form.noticeName"></el-input>
    </el-form-item>

    <el-form-item label="公告内容">
      <el-input type="textarea" v-model="form.noticeContent"></el-input>
    </el-form-item>

    <el-form-item label="公告分类">
      <el-select v-model="form.noticeCategoryId" placeholder="请选择公告分类">
        <el-option
          v-for="item in categoryList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="关联小区">
      <el-select v-model="form.communityId" placeholder="请选择小区">
        <el-option
          v-for="item in communityList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="发布人">
      <el-input v-model="form.noticePerson"></el-input>
    </el-form-item>
  </el-form>

  <template #footer>
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitForm">确 定</el-button>
  </template>
</el-dialog>
   
     <!-- 编辑公告弹窗 -->
<el-dialog 
  title="编辑公告" 
  :visible.sync="editDialogVisible" 
  width="500px"
>
  <el-form :model="editForm" label-width="100px">
    <el-form-item label="公告名称">
      <el-input v-model="editForm.noticeName"></el-input>
    </el-form-item>
    <el-form-item label="公告内容">
      <el-input type="textarea" v-model="editForm.noticeContent"></el-input>
    </el-form-item>

    <el-form-item label="公告分类">
  <el-select v-model="editForm.noticeCategoryId" placeholder="请选择公告分类">
    <el-option
      v-for="item in categoryList"
      :key="item.id"
      :label="item.name"  
      :value="item.id"    
    />
  </el-select>
</el-form-item>

<el-form-item label="关联小区">
  <el-select v-model="editForm.communityId" placeholder="请选择小区">
    <el-option
      v-for="item in communityList"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</el-form-item>
    <el-form-item label="发布人">
      <el-input v-model="editForm.noticePerson"></el-input>
    </el-form-item>
  </el-form>

  <template #footer>
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitEditForm">确 定</el-button>
  </template>
</el-dialog>

      
  </div>
  
</template>

<script>


export default {
  data() {
    return {
      tableData: [],
      allTableData: [],     // 保存完整数据
      currentPage: 1,
      pageSize: 3,
      total: 0,
      keyword: "",
      dialogVisible: false,  // 添加 dialogVisible 属性
      editDialogVisible: false, // 编辑公告
      form: {  // 添加 form 属性
        noticeName: '',
        noticeContent: '',
        noticeCategoryId: '',
        communityId: '',
        noticePerson: ''
      },
       editForm: {              // 编辑表单
      noticeId: '',
      noticeName: '',
      noticeContent: '',
      noticeCategoryId: null,
      communityId: null,
      noticePerson: ''
       },
       categoryList: [{id:156116161,name:'普通'} ],  
       communityList: [{id:1968125183214604288,name:"云海"}]   
    };
  },
   
   

  created() {
    this.fetchTable();
  },
  methods: {
    // 获取列表/搜索
fetchTable() {
  if (this.keyword) {
    // 搜索走 GET
    this.$axios.get("http://localhost:8080/notice/search", {
      params: {
        getNoticeName: this.keyword,
        page: this.currentPage,
        size: this.pageSize
      }
    }).then(res => {
      if (res.data.code === 200) {
        const pageData = res.data.data;  // 这里是 Page 对象
        this.tableData = pageData.records;
        this.total = pageData.total;
      } else {
        this.$message.error(res.data.msg);
      }
    }).catch(err => {
      console.error(err);
      this.$message.error("搜索失败");
    });
  } else {
    // 查所有走 POST
    this.$axios.post("http://localhost:8080/notice/all", {
      page: this.currentPage,
      size: this.pageSize,
      keyword: ""   // 可以传空字符串
    }).then(res => {
      if (res.data.code === 200) {
        const pageData = res.data.data; // Page 对象
        this.tableData = pageData.records;
        this.total = pageData.total;
      } else {
        this.$message.error(res.data.msg);
      }
    }).catch(err => {
      console.error(err);
      this.$message.error("获取公告列表失败");
    });
  }
},

 handlePublish() {
      // 发布公告的逻辑
      console.log('发布公告', this.form);
      this.dialogVisible = false;
    },
    handleClose() {
      this.$refs.form.resetFields();
    },

    // 修改编辑
submitEditForm() {
  this.$axios.put(`http://localhost:8080/notice/update`, this.editForm)
    .then(res => {
      if (res.data.code === "200" || res.data.code === 200) {
        this.$message.success("公告修改成功");
        this.editDialogVisible = false;
        this.fetchTable(); // 刷新列表
      } else {
        this.$message.error(res.data.msg);
      }
    })
    .catch(err => {
      console.error("修改失败:", err);
      this.$message.error("公告修改失败");
    });
},
    

    // 删除
  handleDel(row) {
  this.$confirm("确认删除该公告吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      this.$axios.delete(`http://localhost:8080/notice/delete/${row.noticeId}`)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success("删除成功");

            // 如果当前页删除后可能空，页码回退
            const newTotal = this.total - 1;
            const totalPages = Math.ceil(newTotal / this.pageSize);
            if (this.currentPage > totalPages) {
              this.currentPage = totalPages;
            }

            // 刷新表格
            this.fetchTable(); 
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch(() => {
          this.$message.error("删除失败");
        });
    })
    .catch(() => {});
},


   // 发布公告
submitForm() {
  // 校验必填项
  if (!this.form.noticeName || !this.form.noticeContent || !this.form.noticeCategoryId || !this.form.communityId || !this.form.noticePerson) {
    this.$message.warning("请填写完整信息！");
    return;
  }

  // 发送请求到后端
  this.$axios.post("http://localhost:8080/notice/add", this.form)
    .then(res => {
      if (res.data.code === 200 || res.data.code === "200") {
        this.$message.success("公告发布成功");
        this.dialogVisible = false;

        // 重置表单
        this.form = {
          noticeName: '',
          noticeContent: '',
          noticeCategoryId: null,
          communityId: null,
          noticePerson: ''
        };

        // 刷新表格
        this.fetchTable();
      } else {
        this.$message.error(res.data.msg);
      }
    })
    .catch(err => {
      console.error("发布公告失败:", err);
      this.$message.error("发布公告失败");
    });
},

handleEdit(row) {
  this.editForm = {
    noticeId: row.noticeId,
    noticeName: row.noticeName,
    noticeContent: row.noticeContent,
   noticeCategoryId: String(row.noticeCategoryId), // 转成字符串
    communityId: String(row.communityId),          // 转成字符串
    noticePerson: row.noticePerson
  };
  this.editDialogVisible = true;
},

    

    // 分页改变
   handleSizeChange(size) {
this.pageSize = size;
  this.currentPage = 1; // 改变页大小默认回第一页
  this.fetchTable();
},

handleCurrentChange(page) {
   this.currentPage = page;
  this.fetchTable();
},
  },
};

</script>

<style scoped>
.app-wrap {
  padding: 20px;
  background: #fff;
}
.tool-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.pagination {
  margin-top: 15px;
  text-align: right;
}
.table-head {
  background: #f5f7fa !important;
}
</style>